package com.cmc.cloud.cmclink.doc.rpcservice.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.cmc.cloud.cmclink.doc.api.document.emums.VoyScheduleEnum;
import com.cmc.cloud.cmclink.doc.rpcservice.VoyScheduleService;
import com.cmc.cloud.cmclink.doc.util.GsonUtil;
import com.cmc.cloud.cmclink.doc.vo.sovo.sovslvoyvo.SoVslvoyScheduleVO;
import com.cmc.cloud.cmclink.svl.api.base.BargeRotationApi;
import com.cmc.cloud.cmclink.svl.api.base.ScheduleApi;
import com.cmc.cloud.cmclink.svl.api.base.req.*;
import com.cmc.cloud.cmclink.svl.api.base.resp.*;
import com.cmes.framework.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lzp
 */
@Slf4j
@Component
public class VoyScheduleServiceImpl implements VoyScheduleService {

    @Resource
    private ScheduleApi scheduleApi;

    @Resource
    private BargeRotationApi bargeRotationApi;

    /**
     * 获取船期信息过滤掉非法的状态,过滤掉N-转船，P-跳港，V-取消的状态，目前不确定是否还有其他的有效状态所以先过滤非正常状态
     *
     * @param voyQueryReqDTO req
     * @return List<VoyQueryRespDTO>
     */
    @Override
    public List<VoyQueryRespDTO> listByCondition(VoyQueryReqDTO voyQueryReqDTO) {
        try {
            CommonResult<List<VoyQueryRespDTO>> listCommonResult = scheduleApi.listByCondition(voyQueryReqDTO);
            log.info("scheduleApi.listByCondition.info:{}", JSON.toJSONString(listCommonResult));
            List<VoyQueryRespDTO> checkedData = listCommonResult.getCheckedData();
            if (CollectionUtil.isNotEmpty(checkedData)) {
                return checkedData.stream().filter(item ->
                        !VoyScheduleEnum.V.getValue().equalsIgnoreCase(item.getScheduleStatus()) && !VoyScheduleEnum.P.getValue().equalsIgnoreCase(item.getScheduleStatus()) && !VoyScheduleEnum.N.getValue().equalsIgnoreCase(item.getScheduleStatus())
                ).collect(Collectors.toList());
            } else {
                return Collections.emptyList();
            }
        } catch (Exception e) {
            log.error("scheduleApi.listByCondition.error:{}", e.getMessage());
            return Collections.emptyList();
        }
    }

    /**
     * 获取船期信息过滤掉非法的状态,过滤掉N-转船，P-跳港，V-取消的状态，目前不确定是否还有其他的有效状态所以先过滤非正常状态
     * 船名航次+港口只会有一条数据
     *
     * @param dto dto
     * @return List<VesselVoyRespDTO>
     */
    @Override
    public List<VesselVoyRespDTO> listVesselVoy(VesselVoyReqDTO dto) {
        try {
            log.info("scheduleApi.listVesselVoy_request：{}", JSON.toJSONString(dto));
            CommonResult<List<VesselVoyRespDTO>> listCommonResult = scheduleApi.listVesselVoy(dto);
            log.info("scheduleApi.listVesselVoy_response:{}", JSON.toJSONString(listCommonResult));
            List<VesselVoyRespDTO> checkedData = listCommonResult.getCheckedData();
            if (CollectionUtil.isNotEmpty(checkedData)) {
                return checkedData.stream().filter(item ->
                        !VoyScheduleEnum.V.getValue().equalsIgnoreCase(item.getScheduleStatus()) && !VoyScheduleEnum.P.getValue().equalsIgnoreCase(item.getScheduleStatus()) && !VoyScheduleEnum.N.getValue().equalsIgnoreCase(item.getScheduleStatus())
                ).collect(Collectors.toList());
            } else {
                return Collections.emptyList();
            }
        } catch (Exception e) {
            log.error("scheduleApi.listVesselVoy.error:{}", e.getMessage());
            return Collections.emptyList();
        }
    }

    @Override
    public List<SoVslvoyScheduleVO> getLineScheduleByPolPod(PolPodReqDTO polPodReq) {
        List<SoVslvoyScheduleVO> scheduleList = new ArrayList<>();
        CommonResult<List<SchedulePolAndPodRespDTO>> result = scheduleApi.getByPolAndPod(polPodReq);
        List<String> errorList = Arrays.asList(VoyScheduleEnum.V.getValue(), VoyScheduleEnum.P.getValue(), VoyScheduleEnum.N.getValue());
        if (result != null && CollectionUtil.isNotEmpty(result.getData())) {
            for (SchedulePolAndPodRespDTO e : result.getData()) {
                SoVslvoyScheduleVO newSchedule = new SoVslvoyScheduleVO();
                SchedulePolRespDTO pol = e.getPolRespDTO();
                SchedulePodRespDTO pod = e.getPodRespDTO();
                //"异常状态，N-转船，P-跳港，V-取消，A-加靠，记录航期的异常情况，没值表示正常",
                if (StringUtils.isNotEmpty(pol.getScheduleStatus()) && errorList.contains(pol.getScheduleStatus())) {
                    continue;
                }
                newSchedule.setVesselCode(pol.getVesselCode());
                newSchedule.setVoyageEx(pol.getExVoy());
                newSchedule.setLaneCodeEx(pol.getExLaneCode());
                newSchedule.setPolCode(pol.getPortCode());
                newSchedule.setPolTerminal(pol.getTerminalCode());
                newSchedule.setPolEtd(pol.getEtd());

                newSchedule.setVoyageIm(pod.getImVoy());
                newSchedule.setLaneCodeIm(pod.getImLaneCode());
                newSchedule.setPodCode(pod.getPortCode());
                newSchedule.setPodTerminal(pod.getTerminalCode());
                newSchedule.setPodEta(pod.getEta());
                scheduleList.add(newSchedule);
            }
        }
        return scheduleList;
    }

    @Override
    public List<SoVslvoyScheduleVO> multiLineScheduleByPolPod(BargePolPodReqDTO bargePolPodReqDto) {
        List<SoVslvoyScheduleVO> scheduleList = new ArrayList<>(32);
        try {
            CommonResult<List<BargePolAndPodRespDTO>> commonResult = bargeRotationApi.listPolAndPod(bargePolPodReqDto);
            if (commonResult != null && CollectionUtil.isNotEmpty(commonResult.getData())) {
                for (BargePolAndPodRespDTO e : commonResult.getData()) {
                    SoVslvoyScheduleVO newSchedule = new SoVslvoyScheduleVO();
                    BargePolRespDTO pol = e.getPolRespDTO();
                    BargePodRespDTO pod = e.getPodRespDTO();
                    //"异常状态，N-转船，P-跳港，V-取消，A-加靠，记录航期的异常情况，没值表示正常",
                    if (pol.getEnabled()) {
                        newSchedule.setVesselCode(pol.getTransportCode());
                        newSchedule.setVoyageEx(pol.getExVoy());
                        newSchedule.setPolCode(pol.getPortCode());
                        newSchedule.setPolTerminal(pol.getTerminalCode());
                        newSchedule.setPartnerCode(pol.getPartnerCode());
                        if (null != pol.getEtd()) {
                            newSchedule.setPolEtd(pol.getEtd().format(DateTimeFormatter.ISO_LOCAL_DATE));
                        }
                        if (null != pol.getAtu()) {
                            newSchedule.setPolAtu(pol.getAtu().format(DateTimeFormatter.ISO_LOCAL_DATE));
                        }
                        newSchedule.setVoyageIm(pod.getImVoy());
                        newSchedule.setPodCode(pod.getPortCode());
                        if (null != pod.getEta()) {
                            newSchedule.setPodEta(pod.getEta().format(DateTimeFormatter.ISO_LOCAL_DATE));
                        }
                        if (null != pod.getAtb()) {
                            newSchedule.setPodAtb(pod.getAtb().format(DateTimeFormatter.ISO_LOCAL_DATE));
                        }
                        scheduleList.add(newSchedule);
                    }
                }
            }
        } catch (Exception e) {
            log.info("请求获取驳船航线船期数据{0}", GsonUtil.getGson().toJson(bargePolPodReqDto));
            log.error("获取驳船航线船期失败：{0}", e.getMessage());
            return Collections.emptyList();
        }
        return scheduleList;
    }

    @Override
    public LocalDate multiBargeSchedule(BargeQueryReqDTO bargeQueryReqDto) {
        LocalDate localDate = null;
        try {
            CommonResult<List<BargeRotationRespVO>> commonResult = bargeRotationApi.list(bargeQueryReqDto);
            localDate = commonResult.getData().get(0).getAta();
        } catch (Exception e) {
            log.error("请求船期报错入参：{0}异常信息{1}", JSON.toJSONString(bargeQueryReqDto), e.getMessage());
        }

        return localDate;
    }
}
